import axios, { AxiosRequestConfig } from 'axios'

import { IOrderListItem, IOrderListReq, IOrderListRes } from '../interface'
import { normalizeReqData } from '../utils'
import './__mock__'

/** 获取运单列表 */
export const apiGetOrderList = async (
  req: IOrderListReq,
  signal?: AxiosRequestConfig['signal'],
): Promise<IOrderListRes> => {
  const data = normalizeReqData(req)
  const waybillNos = (data.waybillNos?.trim() || undefined)?.split(/\s*\n+\s*/)
  return axios.post(`/tmsapi/waybill_record/list`, { ...data, waybillNos }, { signal }).then(res => ({
    ...res.$data,
    // 空值处理 & 箱数累计
    records: ((res.$data.records || []) as IOrderListItem[]).map(item => {
      let $boxNum = null as number | null
      return {
        ...item,
        boxes: (item.boxes || []).map(d => {
          $boxNum = $boxNum ?? 0
          $boxNum += d.boxNum || 0
          return {
            ...d,
            products: d.products || [],
          }
        }),
        $boxNum,
      }
    }),
  }))
}

/** 创建物流订单推送给牛迈 */
export const aptPostCreateShippingOrders = async (
  req: { waybillNos: string[] },
  signal?: AxiosRequestConfig['signal'],
): Promise<{
  failedWaybillMesses: { waybillNo: string; message: string }[]
  succeedWaybillNos: string[]
}> => {
  return axios.post(`/tmsapi/waybill_record/createShippingOrders`, { ...req }, { signal }).then(res => res.$data)
}
